import axios from "axios";
import config from '../config'
import type { InternalAxiosRequestConfig, AxiosResponse, AxiosInstance,Method } from 'axios'
import store from 'store'
import { isMobile } from "./base";
import { ElMessage } from 'element-plus'

console.log('`${config.host}:${config.host}`:', `${config.host}:${config.host}`);

export const instance: AxiosInstance = axios.create({
    baseURL: `${config.host}:${config.port}`,
    timeout: 5000,
    headers: {
        "Content-Type": 'application/json'
    }
})



instance.interceptors.request.use((reqConfig) => {
    return Promise.resolve(reqConfig)
})

instance.interceptors.response.use((response: AxiosResponse) => {
    console.log('response:', response);

    return response.data.data
})

export interface ReqConfig {
    method?: Method
    needToken?: boolean
    toast?: boolean
    [key: string]: any
}

export async function request(config: ReqConfig) {
    const { method, needToken, toast } = config
    console.log('config:', config);

    const reqParams: any = {
        ...config,
        method: method || 'get',  // 默认get方法
    }
    delete reqParams.needToken
    delete reqParams.toast

    if (needToken) {
        reqParams.headers['token'] = store.get('token')
    }

    try {
        const res = await instance.request(reqParams)
        return res
    } catch (error) {

        if (toast) {
            if (isMobile) {
                console.log('移动端');

            } else {
                ElMessage('This is a message.')
            }
        }
        return Promise.reject(error)
    }
}


